//
//  hysxqViewController.m
//  gangquOASystem
//
//  Created by michael on 2018/8/16.
//  Copyright © 2018年 czd. All rights reserved.
//
#import "bianjihysViewController.h"
#import "OASetMeetingOpinionController.h"
#import "ggxqViewController.h"
#import "OADetailDisPatchController.h"
#import "OADetailDisPatchCell.h"
#import "GDataDefines.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OAAttachmentsModel.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "OADetailDispatchModel.h"
#import "OAReadRecordController.h"
#import "hysxqViewController.h"

@interface hysxqViewController ()<UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>
@property(nonatomic,strong)OADetailDispatchModel * detailPatchModel ;
@property(nonatomic,strong)NSMutableArray * attachmentArray; //附件
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,strong)NSMutableArray * contentsData;

@property(nonatomic,assign)BOOL isEditoring; //编辑中
@property(nonatomic,strong)NSMutableArray * departments;

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * textString ; //记录填写的意见
@property(nonatomic,copy)NSString * body;
@property(nonatomic,strong)NSMutableArray * subItems;  //选中 需要提交得数据

@end

@implementation hysxqViewController
-(NSMutableArray*)contentsData{
    if (_contentsData == nil) {
        _contentsData = [NSMutableArray array];
    }
    return _contentsData;
}

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}
-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}
-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;

}
- (void)viewDidLoad {
    [super viewDidLoad];
//     self.title = @"详情";
//     _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth,self.view.height-kTopHeight-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        self.tableView.backgroundColor = [UIColor whiteColor];
//    _tableView.separatorStyle = NO;
//
//    self.tableView.delegate = self;
//    self.tableView.dataSource =self;
//     [_tableView registerNib:[UINib nibWithNibName:@"TableViewCellstyle1" bundle:nil] forCellReuseIdentifier:@"11"];
//
//    [self.view addSubview:self.tableView];



if ([_type0 isEqualToString:@"shenpi"]) {

    UIBarButtonItem * rightItem1 = [[UIBarButtonItem alloc]initWithTitle:@"同意" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction1)];
    UIBarButtonItem * rightItem2 = [[UIBarButtonItem alloc]initWithTitle:@"不同意" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction2)];


    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
// self.navigationItem.rightBarButtonItem = rightItem;
[self.navigationItem setRightBarButtonItems:@[rightItem1,rightItem2,rightItem]];

}

//    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
// self.navigationItem.rightBarButtonItem = rightItem;

     self.method = @"contentMeetroom";
self.url = @"exchassistant";
[self loadData];
    // Do any additional setup after loading the view.
}
- (void)historyAction1{

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

    NSArray * array =@[@{@"unid":_fileId},@{@"sName":userId}];
[HttpTools postWithURL:@"exchassistant" arrays:array method:@"genagreeMeetroom"  success:^(id JSON) {
 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        if ([message isEqualToString:@"20"]) {
            [self.view.window makeToast:@"保存成功"];
//[self performSelector: @selector(popaction) withObject: nil afterDelay:1.0f];

}else{
        [self.view.window makeToast:@"保存失败"];

}
 } failure:^(NSError *error) {
        [self.view.window makeToast:@"保存失败"];
    }];

}
- (void)historyAction2{

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

    NSArray * array =@[@{@"unid":_fileId},@{@"sName":userId}];
[HttpTools postWithURL:@"exchassistant" arrays:array method:@"disagreegenMeetroom"  success:^(id JSON) {
 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        if ([message isEqualToString:@"20"]) {
            [self.view.window makeToast:@"保存成功"];
//[self performSelector: @selector(popaction) withObject: nil afterDelay:1.0f];

}else{
        [self.view.window makeToast:@"保存失败"];

}
 } failure:^(NSError *error) {
        [self.view.window makeToast:@"保存失败"];
    }];

}
- (void)historyAction{

bianjihysViewController *vc = [[bianjihysViewController alloc]init];
vc.fieid = _fileId;
[self.navigationController pushViewController:vc animated:YES];
}
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

    _array = @[@{@"unId":self.fileId},@{@"userId":userId}];
  
    [HttpTools postWithURL:self.url arrays:_array method:_method success:^(id JSON) {
    
   NSLog(@"====%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
//        ||[self.type isEqualToString:@"shouwen"]||[self.type isEqualToString:@"shiwei"]
   if ([self.type isEqualToString:@"zhuanfa"]||[self.type isEqualToString:@"gonggao"]||[self.type isEqualToString:@"dzgg"]||[self.type isEqualToString:@"xxjb"]||[self.type isEqualToString:@"HYS"]) {
    self.detailPatchModel = [self getDetailModel3:JSON];

        [self.tableView reloadData];
    }
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
-(OADetailDispatchModel *)getDetailModel3:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *data in rootData) {
      
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
        
        
        
            GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
        
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
        
        
    }
    //index。seston = 2
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.detailPatchModel.formArray.count;
            break;
        case 1:
            return self.mainattachmentArray.count;
        case 2:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        OADetailDisPatchCell * cell = [OADetailDisPatchCell cellWihtTableView:tableView];
   //     cell.textView.delegate = self;
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        cell.detailModel = self.detailPatchModel;
        cell.allString = allString;
         [cell editStatus:self.isEditoring];
        return cell;
    }else{

        if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;
            
        }else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;

        }

    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        CGFloat height =  [allString boundingRectWithSize:CGSizeMake(KScreenWidth - 30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height;
        if (height < 44) {
            height = 44;
        }
        return height + 10;
    }else{
        return 54;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth, 21)];
        label.text = @"正文";
       // label.backgroundColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
//OAAttachmentsModel * model = self.mainattachmentArray[0];
   if (_mainattachmentArray.count>0) {
            OAAttachmentsModel * model = self.mainattachmentArray[0];
            if ([model.attachmentsTitle length]>0) {
        return bgView;

}
else{
        return nil;

}
}else{
        if (!(self.mainattachmentArray.count>0)) {
            label.hidden = YES;
        }else{
            label.hidden = NO;
        }
         if (!(self.mainattachmentArray.count>0)) {
        return nil;
        }else{
        return bgView;
        }
        }
//        return bgView;
    }
     if (section==2) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
//        label.backgroundColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
         if (_attachmentArray.count>0) {
            OAAttachmentsModel * model = self.attachmentArray[0];
            if ([model.attachmentsTitle length]>0) {
        return bgView;

}
else{
        return nil;

}
}else{
     if (!(self.attachmentArray.count>0)) {
            label.hidden = YES;
        }else{
            label.hidden = NO;
        }
         if (!(self.attachmentArray.count>0)) {
        return nil;
        }else{
        return bgView;
        }
        }
//        return bgView;

}
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
    if (_mainattachmentArray.count>0) {
            OAAttachmentsModel * model = self.mainattachmentArray[0];
            if ([model.attachmentsTitle length]>0) {
         return 21;

}
else{
 return 0.001;
//[_mainattachmentArray removeAllObjects];

}
}else{
    if (_mainattachmentArray.count !=0) {
     return 21;

}else{

 return 0.001;


}
    }
//    return 21;
           }
    if (section==2) {
        if (_attachmentArray.count>0) {
            OAAttachmentsModel * model = self.attachmentArray[0];
            if ([model.attachmentsTitle length]>0) {
         return 21;

}
else{
//[_attachmentArray removeAllObjects];
 return 0.001;

}
}else{
 if (_attachmentArray.count!=0) {
     return 21;

}else{

 return 0.001;


}}
//return 21;
    }
    return 0.001;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
// fujianwebViewController *vc = [[fujianwebViewController alloc]init];
//        vc.url = model.attachmentsURL;
//        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
// fujianwebViewController *vc = [[fujianwebViewController alloc]init];
//        vc.url = model.attachmentsURL;
//        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
 
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
//         wordController  *VC = [[wordController alloc] init];
//    VC.attacmentURL =self.attacmentURL;
//    [self.navigationController pushViewController:VC animated:YES];

        
    }else{
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webview loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
     [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
      return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//            UIViewController *vc = [[UIViewController alloc] init] ;
//      QLPreviewController *HPQLController = [[QLPreviewController alloc] init];
//    HPQLController.dataSource = self;
//    [vc addChildViewController:HPQLController];
//    [HPQLController didMoveToParentViewController:self];
//    [vc.view addSubview:HPQLController.view];
//    HPQLController.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
//    vc.hidesBottomBarWhenPushed = NO;
//    [self.navigationController pushViewController: vc animated:YES];

//       wordController  *VC = [[wordController alloc] init];
//    VC.attacmentURL =self.attacmentURL;
//    [self.navigationController pushViewController:VC animated:YES];
    
    
    

    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
    
    
    
    
    
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
